<?php

/**
 * @author Lam Vu Nhat
 * @copyright 2011
 */
class Muare_Cache_Core
{
	/**
	 * Object
	 *
	 * @var Zend_Cache_Core
	 */
	protected $_cache = null;

	/**
	 * Constructor
	 */
	public function __construct()
	{
		if (XenForo_Application::get('config')->cache->enabled
			&& XenForo_Application::get('cache') instanceof Zend_Cache_Core)
		{
			$this->_cache = XenForo_Application::get('cache');
		}
	}

	/**
	 * Test if a cache is available for the given id and (if yes) return it (false else)
	 *
	 * @param string $id
	 */
	public function load($id)
	{
		if (!$this->_cache) return false;

		// Load cache data
		$data = $this->_cache->load($this->_cacheId($id));

		// Miss cache ... ... ...
		if ($data === false) return false;

		return unserialize($data);
	}

	/**
	 * Save some data in a cache
	 * Using id is last id from load function
	 *
	 * @param string | array $data
	 * @param interger $lifeTime
	 */
	public function save($data, $lifeTime = 0)
	{
		if (!$this->_cache) return false;

		// Set cache life time
		$this->_cache->setLifetime($lifeTime);

		// Compress data to save
		if (is_array($data)) $data = serialize($data);

		return $this->_cache->save($data);
	}

	/**
	 * Remove a cache
	 *
	 * @param  string $id Cache id to remove
	 * @return boolean True if ok
	 */
	public function remove($id)
	{
		if (!$this->_cache) return false;

		return $this->_cache->remove($this->_cacheId($id));
	}

	/**
	 * Buid a prefix cache
	 *
	 * @param string $id
	 * @return string
	 */
	protected function _cacheId($id)
	{
		return 'Muare_' . $id;
	}
}
